package com.autism.my_lock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class LockDemo implements Runnable {
    //定义票源
    private int ticket = 100;

    Lock lock = new ReentrantLock();

    //设置线程任务：卖票
    @Override
    public void run() {
        while (true) {

            //获取锁
            lock.lock();
            //同步代码块
            if (ticket > 0) {
                try {
                    Thread.sleep(1000);
                    System.out.println(Thread.currentThread().getName() + ":" + ticket + "张票");
                    ticket--;
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    //释放锁(无论程序是否异常)
                    lock.unlock();
                }
            }
        }
    }
}
